package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext servletContext;

    @GetMapping
    public List<Region> listAll(Integer state){
        return regionService.listAll(state);
    }

    /**
     * 获取json
     * @param qo
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo listStrategiesJson(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        qo.setPageSize(8);
        return strategyService.query(qo);
    }

        /**
         * 获取html
         * @param qo
         * @param response
         * @throws Exception
         */
    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void listStrategiesHtml(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //获取当季数据
        qo.setPageSize(0);
        qo.setState(Strategy.STATE_ABLE);
        PageInfo<?> commends = strategyService.query(qo);

        //获取全部攻略的数据
        qo.setPageSize(8);
        qo.setState(null);//查全部
        PageInfo<?> alls = strategyService.query(qo);

        //使用freemarker合并模板和数据
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //设置模板目录位置(当前项目的webapp下的template目录)
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
        //获取模板文件
        Template template = configuration.getTemplate("strategyTemplate.ftl", "utf-8");
        //数据
        HashMap<Object, Object> map = new HashMap<>();
        map.put("commends",commends);
        map.put("alls",alls);
        //合并数据,并响应回浏览器
        template.process(map,response.getWriter());
    }

}
